<template>
  <div class="app-container warehouse-content">
    <BtnGroup ref="btnGroup" :btns="btns" @handle="handleBtnGroup" />
    <!-- 工具栏 end-->

    <div class="">
      <el-table
        ref="table"
        v-loading="loading"
        :data="lists"
        :height="st"
        style="width: 100%"
        row-key="id"
        lazy
      >
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column label="仓库编号">
          <template slot-scope="scope">
            <el-form :model="scope.row">
              <el-form-item size="mini">
                <el-input
                  v-if="scope.row.isOK"
                  v-model="scope.row.warehouse_code"
                ></el-input>
                <span class="spspsp" v-else>{{
                  scope.row.warehouse_code
                }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="仓库简称">
          <template slot-scope="scope">
            <span>{{ scope.row.warehouse_short_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="仓库全称">
          <template slot-scope="scope">
            <span>{{ scope.row.warehouse_name }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="editFrom(scope.row)"
              >设置规则
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        ref="paginationTotal"
        :page="currentPage"
        :total="total"
        :size="pageSize"
        @sizeChange="sizeChange"
        @currentChange="currentChange"
      />
    </div>

    <!--新建仓库 弹框-->
    <el-dialog
      class="set-dialog"
      :visible.sync="dialogVisible"
      title="设置规则"
      :before-close="modalClose"
      :close-on-press-escape="false"
      append-to-body
    >
      <div>
        <el-form label-width="180px" size="small">
          <el-form-item class="front" label="溯源：">
            <el-radio-group
              v-model="traceBackSetting.switch"
              :disabled="!traceBackSetting.state"
            >
              <el-radio :label="3">全部商品开启</el-radio>
              <el-radio :label="4">部分商品开启</el-radio>
            </el-radio-group>
            <el-switch
              style="margin-left: 20px"
              v-model="traceBackSetting.state"
              @change="traceChange()"
            >
            </el-switch>
            <p class="edit-tips">
              仓库必须有相应的硬件设备支撑才可使用此功能。若强制开启会造成仓库无法进行出入库作业。
              您可选仓库全部商品开启；也可选择仅对部分高货值商品开启。
            </p>
          </el-form-item>
          <el-form-item
          
            label="溯源："
            v-if="traceBackSetting.switch == 4"
          >
            <el-link :underline="false" type="primary" @click="showGoodsDetail"
              >商品资料明细</el-link
            >
            
          </el-form-item>
          <el-form-item label="数据延时推送：" class="front">
            <el-input
              v-model.trim="delayDeliverySetting.time_delay"
              placeholder="请输入数据延时几小时推送"
            >
              <template slot="append">小时</template></el-input
            >
            <p class="edit-tips">
              设置延时推送后，仓储系统的产生的数据，将会按照设置时间推送给第三方系统。在数据未推送第三方系统时，您可在仓储系统进行数据反审操作；已推送到第三方系统的数据，如需反审请联系第三方系统协商解决。
            </p>
          </el-form-item>

          <!-- <el-form-item label="快捷入口：" prop="user_name"> </el-form-item> -->

          <el-form-item label="出库原则：">
            <div>
              <span class="date-left-tips">1.近效期先出</span>
              <el-radio-group
                v-model="dateFirstSetting.switch"
                :disabled="!dateFirstSetting.state"
              >
                <el-radio :label="1">精确至商品</el-radio>
                <el-radio :label="2">精确至仓位</el-radio>
              </el-radio-group>
              <el-switch
                style="margin-left: 20px"
                v-model="dateFirstSetting.state"
                @change="dateFirstSettingChange()"
              >
              </el-switch>
            </div>
            <div>
              <span class="date-left-tips">2.入库先进先出</span>
              <el-radio-group
                v-model="interFirstSetting.switch"
                :disabled="!interFirstSetting.state"
              >
                <el-radio :label="1">精确至商品</el-radio>
                <el-radio :label="2">精确至仓位</el-radio>
              </el-radio-group>
              <el-switch
                style="margin-left: 20px"
                v-model="interFirstSetting.state"
                @change="interFirstSettingChange()"
              >
              </el-switch>
            </div>
            <div>
              <span class="date-left-tips">3.无规则</span>

              <el-switch
                style="margin-left: 20px"
                v-model="notRuleSetting.state"
              >
              </el-switch>
            </div>
          </el-form-item>
        </el-form>

        <div class="tool2" style="margin-top: 45px">
          <el-button type="primary" size="medium" @click="handleSubmit"
            >确定</el-button
          >
          <el-button size="medium" @click="modalClose">取消</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 溯源商品明细 -->
    <el-dialog class="set-dialog" :visible.sync="traceDialog" title="明细">
      <div>
        <el-button size="small" @click="addGoodsBtn">添加商品</el-button>

        <el-button size="small" @click="delDetailGoods">删除</el-button>
        <el-button size="small"  @click="downloadInventory()"
          >下载</el-button
        >
      </div>
      <el-table :data="waitSureGoodsList" ref="detailTable" border height="500">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="商品名称"></el-table-column>
        <el-table-column label="属性">
          <template slot-scope="scope">
            <p v-for="attr in scope.row.newAttr" :key="attr">{{ attr }}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="inside_product_no"
          label="内部商品编号"
        ></el-table-column>
        <el-table-column
          prop="outside_product_no"
          label="外部商品编号"
        ></el-table-column>
        <el-table-column prop="barcode" label="商品条码"></el-table-column>
        <el-table-column prop="unit" label="单位"></el-table-column>
        <el-table-column label="是否含有危险品">
          <template slot-scope="scope">
            <span>{{ scope.row.is_dangerous == 1 ? "是" : "否" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品质量">
          <template slot-scope="scope">
            <p>{{ scope.row.is_damaged == 0 ? "完好" : "破损" }}</p>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 添加商品 弹窗 -->
    <el-dialog
      class="add-goods-dialog"
      :visible.sync="goodsDialog"
      title="添加商品"
    >
      <div class="shelf-dialog">
        <EzForm
          :formMap="goodsFormMap"
          v-model="goodsFormData"
          @search="goodsRequest"
        ></EzForm>
        <div>
          <el-button type="primary" size="medium" @click="sureChooseBtn"
            >确定保存</el-button
          >
        </div>
        <el-table
          :data="goodsList"
          ref="goodsTable"
          border
          height="500"
          highlight-current-row
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="name" label="商品名称"></el-table-column>
          <el-table-column label="属性">
            <template slot-scope="scope">
              <p v-for="attr in scope.row.newAttr" :key="attr">{{ attr }}</p>
            </template>
          </el-table-column>
          <el-table-column
            prop="inside_product_no"
            label="内部商品编号"
          ></el-table-column>
          <el-table-column
            prop="outside_product_no"
            label="外部商品编号"
          ></el-table-column>
          <el-table-column prop="barcode" label="商品条码"></el-table-column>
          <el-table-column prop="unit" label="单位"></el-table-column>
          <el-table-column label="是否含有危险品">
            <template slot-scope="scope">
              <span>{{ scope.row.is_dangerous == 1 ? "是" : "否" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="商品质量">
            <template slot-scope="scope">
              <p>{{ scope.row.is_damaged == 0 ? "完好" : "破损" }}</p>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="code" label="可售库存"> </el-table-column>
          <el-table-column prop="code" label="实际库存"> </el-table-column>
          <el-table-column prop="code" label="占用库存"> </el-table-column> -->
        </el-table>
        <pagination
          ref="paginationTotal"
          :page="goodsCurrentPage"
          :total="goodsTotal"
          :size="goodsPageSize"
          @sizeChange="goodsSizeChange"
          @currentChange="goodsCurrentChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { getList } from '@/api/table'
export default {
  data() {
    return {
      formData: {
        warehouse_code: "",
        warehouse_short_name: "",
        warehouse_name: "",
        user_name: "",
        phone: "",
        overflow: "",
        in_charge_name: "",
        created_at: "",
        updated_at: "",
        expire_time: "",
        province: "",
        city: "",
        area: "",
      },
      btns: [
        // { title: "维护入库类型", pos: "right", handle: "enterType" },
        { title: "查看日志", pos: "right", handle: "log" },
        // { title: "取消溢出", pos: "right", handle: "cancle" },
        // { title: "设为溢出", pos: "right", handle: "set" },
        // { title: "暂停仓库", pos: "right", handle: "close" },
        // { title: "开启仓库", pos: "right", handle: "open" },
        // { title: "新增", pos: "right", handle: "new" },
      ],

      goodsFormMap: [
        {
          label: "商品名称",
          key: "name",
          type: "input",
        },
        {
          label: "商品条码",
          key: "barcode",
          type: "input",
        },
        {
          label: "商品内部编码",
          key: "inside_product_no",
          type: "input",
        },
        {
          label: "商品外部编码",
          key: "outside_product_no",
          type: "input",
        },
        {
          label: "商品分类",
          key: "classify_id",
          type: "select",
          options: [],
        },
        {
          label: "是否危险品",
          key: "is_dangerous",
          type: "select",
          options: [
            { label: "是", value: "1" },
            { label: "否", value: "0" },
          ],
        },
      ],
      goodsFormData: {
        name: "", //商品名称
        inside_product_no: "", //内部商品编码
        outside_product_no: "", //外部商品编码
        inside_style_no: "", //内部款式编码
        outside_style_no: "", //外部款式编码
        classify_id: "", //产品分类id
        is_dangerous: "", //是否危险品【1：是，0：否】
      },
      goodsDialog: false,
      warehouseId: "",

      //溯源商品明细
      traceDialog: false,
      waitSureGoodsList: [], //带确认商品列表
      orderNo: "", //
      goodsList: [], //商品列表
      // 默认显示第几页
      goodsCurrentPage: 1,
      // 总条数，根据接口获取数据长度(注意：这里不能为空)
      goodsTotal: 0,
      // 个数选择器（可修改）
      goodsPageSizes: [50, 100, 200],
      // 默认每页显示的条数（可修改）
      goodsPageSize: 30,
      lists: [],
      dialogloading: false,
      loading: false,

      //溯源
      traceBackSetting: {
        id: "", //id
        type: "", //溯源
        switch: "1", //3：全部商品，4：部分商品
        state: "", //开启状态【1：开启，0：关闭】
      },

      //数据延时推送
      delayDeliverySetting: {
        id: "", //id
        type: "", //数据延时推送
        time_delay: "", //延迟时间
        switch: "",
        state: 1, //开启状态【1：开启，0：关闭】
      },
      //（出库）近有效期先出
      dateFirstSetting: {
        id: "", //id
        type: "", //（出库）近有效期先出
        switch: "", //1：精确至商品，2：精确至仓位
        state: "", //开启状态【1：开启，0：关闭】
      },
      //（出库）入库先进先出
      interFirstSetting: {
        id: "", //id
        type: "", //（出库）入库先进先出
        switch: "", //1：精确至商品，2：精确至仓位
        state: "", //开启状态【1：开启，0：关闭】
      },
      //无规则
      notRuleSetting: {
        id: "", //id
        type: "", //出库）无限制
        switch: "", //1：精确至商品，2：精确至仓位
        state: "", //开启状态【1：开启，0：关闭】
      },

      // 默认显示第几页
      currentPage: 1,
      // 总条数，根据接口获取数据长度(注意：这里不能为空)
      total: 0,
      // 个数选择器（可修改）
      pageSizes: [50, 100, 200],
      // 默认每页显示的条数（可修改）
      pageSize: 30,

      st: 0,
      dialogVisible: false,
      dialogTitle: "新建仓库",
      isEdit: false, //是否编辑
      addform: {
        id: "", //新建不需要传
        warehouse_name: "", //仓库全称
        warehouse_short_name: "", //仓库简称
        user_name: "", //联系人姓名
        phone: "", //联系人手机
        in_charge_name: "", //仓库负责人
        warehouse_parent_id: "", //创建父账号
        warehouse_parent_phone: "", //父账号手机号
        password: "", //密码
        province: "", //仓库所在省份ID
        city: "", //仓库所在城市ID
        area: "", //仓库所在区域ID
        address: "", //仓库所在详细地址
        expire_time: "", //到期日期
        front: "", //是否前置仓[0.否 1.是]
        remark: "", //备注
        in_charge_id: "", //仓库负责人ID
      },

      in_charge_name: [], //仓库负责人
    };
  },

  created() {
    this.handleRequest();
  },

  mounted() {
    const that = this;
    that.$util.autoHeight(that, that.$refs.table.$el);
  },
  methods: {
    /**
     * 头部按钮列表
     */
    handleBtnGroup(evt) {
      let { handle } = evt;
      switch (handle) {
        case "new":
          this.handleCreate();
          break;
        case "search":
          this.handleRequest();
          break;

        case "log":
          this.toLog();
          break;
        default:
          break;
      }
    },
    //下载
    async downloadInventory() {
      const that = this;

      try {
        // const { result } = await that.$.util.downloadPackStandard();
        that.$message({ type: "success", message: "已提交下载申请" });
      } catch (e) {}
    },
    /**
     * 溯源商品列表
     */
    async traceProductList(item) {
      const { result } = await this.$.product.productList({
        trace_back: 1,
        warehouse_id: this.warehouseId,
      });
      result.list.map((item) => {
        item.newAttr = [];
        item.attribute.map((sitem, sindex) => {
          let key = "attribute" + (sindex + 1);
          item.newAttr.push(sitem[key]);
        });
      });
      this.waitSureGoodsList = result.list;
    },
    // 添加商品的弹窗
    addGoodsBtn() {
      this.goodsDialog = true;
      this.goodsRequest();
    },
    // 取消溯源
    async delDetailGoods() {
      let that = this;
      let _selectData = that.$refs.detailTable.selection;
      let ids = [];
      _selectData.forEach((item, i) => {
        item.newAttr = [];
        item.attribute.map((sitem, sindex) => {
          let key = "attribute" + (sindex + 1);
          item.newAttr.push(sitem[key]);
        });
        ids.push(item.id);
        that.waitSureGoodsList.push(item);
      });
      if (ids.length <= 0) {
        that.$message({ type: "error", message: "请选择需要操作的数据！" });
        return false;
      }
      await that.$.product.setTraceBack({
        ids: ids,
        trace_back: 0,
        warehouse_id: that.warehouseId,
      });

      that.$message({ type: "success", message: "删除成功" });
      that.traceProductList();
    },
    /**
     * 确认选择入库商品
     */
    async sureChooseBtn() {
      let that = this;
      let _selectData = that.$refs.goodsTable.selection;
      let ids = [];
      let goodsArr = [];
      let obj = {};
      _selectData.forEach((item, i) => {
        item.newAttr = [];
        goodsArr.push({
          wh_product_id: item.id,
          trace_back: 1,
        });
        item.attribute.map((sitem, sindex) => {
          let key = "attribute" + (sindex + 1);
          item.newAttr.push(sitem[key]);
        });
        ids.push(item.id);
        that.waitSureGoodsList.push(item);
      });
      if (ids.length <= 0) {
        that.$message({ type: "error", message: "请选择需要操作的商品！" });
        return false;
      }
      await that.$.product.setTraceBack({
        ids: ids,
        trace_back: 1,
        warehouse_id: that.warehouseId,
      });
      that.traceProductList();
      that.$message({ type: "success", message: "提交成功" });
      that.goodsDialog = false;
    },
    /**
     * 获取入库商品列表
     */
    async goodsRequest() {
      const that = this;
      const { goosdsCurrentPage, goodsPageSize } = that;
      let o = {
        page_size: goodsPageSize,
        page: goosdsCurrentPage,
      };
      that.$util.ext(that.goodsFormData, o);
      try {
        that.loading = true;
        const { result } = await this.$.product.productList({
          trace_back: 0,
          warehouse_id: that.warehouseId,
        });
        result.list.map((item) => {
          item.newAttr = [];
          item.attribute.map((sitem, sindex) => {
            let key = "attribute" + (sindex + 1);
            item.newAttr.push(sitem[key]);
          });
        });
        that.goodsTotal = result.pagination.total_count;
        that.$refs.table.bodyWrapper.scrollTop = 0;
        that.goodsList = result.list;
        that.loading = false;
      } catch (e) {
        that.loading = false;
      }
    },

    showGoodsDetail() {
      this.traceDialog = true;
      this.traceProductList();
    },
    /**
     * 查看详情
     */
    editFrom(item) {
      this.dialogVisible = true;
      this.warehouseId = item.id;
      this.settingIndex(item.id);
    },
    traceChange() {
      // this.traceBackSetting.switch = "";
    },
    dateFirstSettingChange() {
      // this.dateFirstSetting.switch = "";
    },
    interFirstSettingChange() {
      // this.interFirstSetting.switch = "";
    },
    /**
     * 获取配置信息
     */
    async settingIndex(id) {
      const { result } = await this.$.authority.settingIndex({
        warehouse_id: id,
      });
      console.log(
        "result.traceBackSetting[0].switch",
        result.traceBackSetting[0].switch
      );
      this.traceBackSetting.switch = result.traceBackSetting[0].switch;
      this.traceBackSetting.type = result.traceBackSetting[0].type;
      this.traceBackSetting.state =
        result.traceBackSetting[0].state == 1 ? true : false;
      this.traceBackSetting.id = result.traceBackSetting[0].id;

      this.delayDeliverySetting.time_delay =
        result.delayDeliverySetting[0].time_delay;
      this.delayDeliverySetting.id = result.delayDeliverySetting[0].id;
      this.delayDeliverySetting.switch = result.delayDeliverySetting[0].switch;

      this.dateFirstSetting.switch = result.warehouseOutSetting[0].switch;
      this.dateFirstSetting.state =
        result.warehouseOutSetting[0].state == 1 ? true : false;
      this.dateFirstSetting.id = result.warehouseOutSetting[0].id;

      this.interFirstSetting.switch = result.warehouseOutSetting[1].switch;
      this.interFirstSetting.state =
        result.warehouseOutSetting[1].state == 1 ? true : false;
      this.interFirstSetting.id = result.warehouseOutSetting[1].id;

      this.notRuleSetting.switch = result.warehouseOutSetting[2].switch;
      this.notRuleSetting.state =
        result.warehouseOutSetting[2].state == 1 ? true : false;
      this.notRuleSetting.id = result.warehouseOutSetting[2].id;
      console.log("result", result);
    },

    /**
     * 查看日志
     */
    toLog() {
      this.$router.push(`/authority/settingLog`);
    },

    /**
     * 关闭对话框
     */
    modalClose() {
      this.dialogVisible = false;
    },
    /**
     * 显示创建账号弹框
     */
    async handleCreate(e) {
      const that = this;
      that.dialogloading = false;
      that.dialogVisible = true;
      that.isEdit = false;

      that.addform = {
        id: "", //新建不需要传
        warehouse_name: "", //仓库全称
        warehouse_short_name: "", //仓库简称
        user_name: "", //联系人姓名
        phone: "", //联系人手机
        in_charge_name: "", //仓库负责人
        warehouse_parent_id: "", //创建父账号
        warehouse_parent_phone: "", //父账号手机号
        password: "", //密码
        province: "", //仓库所在省份ID
        city: "", //仓库所在城市ID
        area: "", //仓库所在区域ID
        address: "", //仓库所在详细地址
        expire_time: "", //到期日期
        front: "", //是否前置仓[0.否 1.是]
        remark: "", //备注
        in_charge_id: "", //仓库负责人ID
      };
    },
    /**
     * 提交创建
     */
    async handleSubmit(e) {
      const that = this;
      that.traceBackSetting.state = that.traceBackSetting.state == true ? 1 : 0;
      that.dateFirstSetting.state = that.dateFirstSetting.state == true ? 1 : 0;
      that.interFirstSetting.state =
        that.interFirstSetting.state == true ? 1 : 0;
      that.notRuleSetting.state = that.notRuleSetting.state == true ? 1 : 0;
      let arr = [];
      arr.push(that.traceBackSetting);
      arr.push(that.dateFirstSetting);
      arr.push(that.delayDeliverySetting);
      arr.push(that.interFirstSetting);
      arr.push(that.notRuleSetting);

      console.log("arr", arr);
      //   return
      const { result } = await that.$.authority.settingEdit(arr);
      that.dialogloading = false;
      that.dialogVisible = false;
      that.$message({ type: "success", message: "修改成功" });
      that.handleSearch();
    },
    /**
     * 搜索
     */
    handleSearch(statu) {
      this.currentPage = 1;
      this.handleRequest();
    },
    /**
     * 弹框的行更改
     */
    rowChange(e) {
      console.log(e);
    },
    sizeChange(e) {
      const that = this;
      that.currentPage = 1;
      that.pageSize = e;
      that.handleRequest();
    },
    currentChange(e) {
      this.currentPage = e;
      this.handleRequest();
    },
    handleSelect() {
      this.currentPage = 1;
      this.handleRequest();
    },
    goodsSizeChange(e) {
      const that = this;
      that.goodsCurrentPage = 1;
      that.goodsPageSize = e;
      that.goodsRequest();
    },
    goodsCurrentChange(e) {
      this.goodsCurrentPage = e;
      this.goodsRequest();
    },

    /**
     * 获取列表
     */
    async handleRequest() {
      const that = this;
      const { currentPage, pageSize, formData } = that;
      // console.log(`handleRequest 第${currentPage}页`);
      let o = {
        page_size: pageSize,
        page: currentPage,
      };
      o.start_created_at = !!formData.created_at ? formData.created_at[0] : "";
      o.end_created_at = !!formData.created_at ? formData.created_at[1] : "";

      o.start_updated_at = !!formData.updated_at ? formData.updated_at[0] : "";
      o.end_updated_at = !!formData.updated_at ? formData.updated_at[1] : "";

      o.start_expire_time = !!formData.expire_time
        ? formData.expire_time[0]
        : "";
      o.end_expire_time = !!formData.expire_time ? formData.expire_time[1] : "";

      that.$util.ext(that.formData, o);

      try {
        that.loading = true;
        const { result } = await that.$.warehouse.warehouseList(that.formData);
        that.total = result.pagination.total_count;
        that.$refs.table.bodyWrapper.scrollTop = 0;
        that.lists = result.list;
        result.list.map((item) => {
          item.isOK = false;
          if (!item.length) return;
          that.in_charge_name.push({ name: item.in_charge_name });
        });
        that.loading = false;
      } catch (e) {
        that.loading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.inp1 {
  flex: 1;
  margin-right: 12px;
}

.supname {
  margin: -18px 0 0 12px;
}

.label {
  font-size: 13px;
  margin-right: 5px;
}
</style>
<style>
.date-left-tips {
  margin-right: 20px;
}
.warehouse-content .cell {
  text-align: center;
}
.set-dialog .form-flex .el-form-item__content {
  display: flex !important;
}
 .set-dialog .front { 
  padding-bottom: 32px !important;

}
.warehouse-content .front .el-form-item__content {
  margin-left: 0 !important;
}
.set-dialog .edit-tips {
  color: #c0c4cc;
  font-size: 12px;
  line-height: 1;
  position: absolute;
  padding-top: 4px;
  top: 100%;
  left: 0;
}
.set-dialog .dev-tips {
  color: #c0c4cc;
  font-size: 12px;
  line-height: 1;
  position: absolute;
  top: 100%;
  left: 0;
}
.set-dialog .copy-btn {
  margin-left: 24px;
}
</style>
